<template>
  <div class="contract-detail-page" v-loading="loading">
    <div class="page-header">
      <el-button @click="$router.back()" class="back-btn">
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
      <h2>合同详情</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleEdit">编辑合同</el-button>
        <el-dropdown @command="handleStatusChange">
          <el-button type="success">
            更新状态
            <el-icon><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="draft">草稿</el-dropdown-item>
              <el-dropdown-item command="reviewing">审核中</el-dropdown-item>
              <el-dropdown-item command="approved">已批准</el-dropdown-item>
              <el-dropdown-item command="signed">已签署</el-dropdown-item>
              <el-dropdown-item command="expired">已过期</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <div class="contract-content" v-if="contractData">
      <el-row :gutter="20">
        <el-col :span="16">
          <!-- 基本信息 -->
          <div class="card">
            <h3>基本信息</h3>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="合同编号">{{ contractData.contractNumber }}</el-descriptions-item>
              <el-descriptions-item label="合同类型">{{ contractData.type }}</el-descriptions-item>
              <el-descriptions-item label="合同标题" :span="2">{{ contractData.title }}</el-descriptions-item>
              <el-descriptions-item label="合同状态">
                <el-tag :type="getStatusTagType(contractData.status)">
                  {{ getStatusText(contractData.status) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="客户">{{ contractData.clientName }}</el-descriptions-item>
              <el-descriptions-item label="合同金额">{{ formatMoney(contractData.amount) }}</el-descriptions-item>
              <el-descriptions-item label="签署日期">
                {{ contractData.signDate ? formatDate(contractData.signDate, 'YYYY-MM-DD') : '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="开始日期">
                {{ formatDate(contractData.startDate, 'YYYY-MM-DD') }}
              </el-descriptions-item>
              <el-descriptions-item label="结束日期">
                {{ formatDate(contractData.endDate, 'YYYY-MM-DD') }}
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">
                {{ formatDate(contractData.createdAt) }}
              </el-descriptions-item>
              <el-descriptions-item label="更新时间">
                {{ formatDate(contractData.updatedAt) }}
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 合同条款 -->
          <div class="card">
            <h3>合同条款</h3>
            <div class="contract-clauses">
              <div v-for="(clause, index) in contractClauses" :key="index" class="clause-item">
                <h4>{{ clause.title }}</h4>
                <p>{{ clause.content }}</p>
              </div>
            </div>
          </div>

          <!-- 审批记录 -->
          <div class="card">
            <h3>审批记录</h3>
            <el-timeline>
              <el-timeline-item
                v-for="item in approvalHistory"
                :key="item.id"
                :timestamp="formatDate(item.createdAt)"
                placement="top"
              >
                <el-card>
                  <h4>{{ item.action }}</h4>
                  <p>{{ item.comment }}</p>
                  <div class="approval-meta">
                    <span>操作人：{{ item.operatorName }}</span>
                  </div>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-col>

        <el-col :span="8">
          <!-- 相关文档 -->
          <div class="card">
            <div class="card-header">
              <h3>相关文档</h3>
              <el-button type="primary" size="small" @click="handleUploadDoc">
                上传文档
              </el-button>
            </div>
            <div class="document-list">
              <div
                v-for="doc in documentList"
                :key="doc.id"
                class="document-item"
                @click="handleDownloadDoc(doc)"
              >
                <el-icon><Document /></el-icon>
                <div class="doc-info">
                  <div class="doc-name">{{ doc.name }}</div>
                  <div class="doc-meta">
                    {{ formatFileSize(doc.size) }} | {{ formatDate(doc.createdAt, 'MM-DD HH:mm') }}
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 相关案件 -->
          <div class="card">
            <div class="card-header">
              <h3>相关案件</h3>
              <el-button type="primary" size="small" @click="handleLinkCase">
                关联案件
              </el-button>
            </div>
            <div class="case-list">
              <div
                v-for="caseItem in caseList"
                :key="caseItem.id"
                class="case-item"
                @click="handleViewCase(caseItem)"
              >
                <div class="case-info">
                  <div class="case-title">{{ caseItem.title }}</div>
                  <div class="case-meta">
                    {{ caseItem.caseNumber }} | {{ caseItem.clientName }}
                  </div>
                </div>
                <el-tag :type="getCaseStatusTagType(caseItem.status)">
                  {{ getCaseStatusText(caseItem.status) }}
                </el-tag>
              </div>
            </div>
          </div>

          <!-- 财务记录 -->
          <div class="card">
            <h3>财务记录</h3>
            <div class="finance-summary">
              <div class="finance-item">
                <span class="label">已收款：</span>
                <span class="value income">{{ formatMoney(financeSummary.received) }}</span>
              </div>
              <div class="finance-item">
                <span class="label">待收款：</span>
                <span class="value pending">{{ formatMoney(financeSummary.pending) }}</span>
              </div>
              <div class="finance-item">
                <span class="label">总金额：</span>
                <span class="value total">{{ formatMoney(contractData.amount) }}</span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 编辑合同对话框 -->
    <ContractForm
      v-model:visible="editVisible"
      :form-data="contractData"
      @success="handleEditSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getContractDetail, updateContractStatus } from '@/api/contract'
import { formatDate, formatMoney, formatFileSize } from '@/utils'
import type { Contract, Document } from '@/types'
import ContractForm from './components/ContractForm.vue'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const editVisible = ref(false)
const contractData = ref<Contract | null>(null)
const documentList = ref<Document[]>([])
const caseList = ref<any[]>([])
const contractClauses = ref<any[]>([])
const approvalHistory = ref<any[]>([])

const financeSummary = reactive({
  received: 0,
  pending: 0
})

const contractId = route.params.id as string

// 获取合同详情
const fetchContractDetail = async () => {
  try {
    loading.value = true
    const data = await getContractDetail(contractId)
    contractData.value = data.contract
    documentList.value = data.documentList || []
    caseList.value = data.caseList || []
    contractClauses.value = data.clauses || []
    approvalHistory.value = data.approvalHistory || []
    Object.assign(financeSummary, data.financeSummary || { received: 0, pending: 0 })
  } catch (error) {
    ElMessage.error('获取合同详情失败')
    router.back()
  } finally {
    loading.value = false
  }
}

// 编辑合同
const handleEdit = () => {
  editVisible.value = true
}

// 编辑成功
const handleEditSuccess = () => {
  fetchContractDetail()
}

// 更新状态
const handleStatusChange = async (status: string) => {
  try {
    await ElMessageBox.confirm(`确定要将合同状态更新为"${getStatusText(status)}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await updateContractStatus(contractId, status)
    ElMessage.success('状态更新成功')
    fetchContractDetail()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('状态更新失败')
    }
  }
}

// 上传文档
const handleUploadDoc = () => {
  ElMessage.info('文档上传功能开发中')
}

// 下载文档
const handleDownloadDoc = (doc: Document) => {
  ElMessage.info('文档下载功能开发中')
}

// 关联案件
const handleLinkCase = () => {
  ElMessage.info('案件关联功能开发中')
}

// 查看案件
const handleViewCase = (caseItem: any) => {
  router.push(`/cases/detail/${caseItem.id}`)
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    draft: 'info',
    reviewing: 'warning',
    approved: 'primary',
    signed: 'success',
    expired: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    draft: '草稿',
    reviewing: '审核中',
    approved: '已批准',
    signed: '已签署',
    expired: '已过期'
  }
  return textMap[status] || status
}

// 获取案件状态标签类型
const getCaseStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    pending: 'warning',
    processing: 'primary',
    completed: 'success',
    closed: 'info'
  }
  return typeMap[status] || 'info'
}

// 获取案件状态文本
const getCaseStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    pending: '待处理',
    processing: '处理中',
    completed: '已完成',
    closed: '已关闭'
  }
  return textMap[status] || status
}

onMounted(() => {
  fetchContractDetail()
})
</script>

<style lang="scss" scoped>
.contract-detail-page {
  .page-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    
    .back-btn {
      margin-right: 16px;
    }
    
    h2 {
      flex: 1;
      margin: 0;
    }
    
    .header-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .contract-content {
    .card {
      background: #fff;
      border-radius: 8px;
      padding: 20px;
      margin-bottom: 20px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      
      h3 {
        margin: 0 0 16px 0;
        font-size: 16px;
        font-weight: 600;
      }
      
      .card-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 16px;
        
        h3 {
          margin: 0;
        }
      }
    }
    
    .contract-clauses {
      .clause-item {
        margin-bottom: 20px;
        padding: 16px;
        background: #f8f9fa;
        border-radius: 4px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        h4 {
          margin: 0 0 8px 0;
          font-size: 14px;
          font-weight: 600;
          color: #409eff;
        }
        
        p {
          margin: 0;
          line-height: 1.6;
        }
      }
    }
    
    .approval-meta {
      margin-top: 8px;
      font-size: 12px;
      color: #909399;
    }
    
    .document-list,
    .case-list {
      .document-item,
      .case-item {
        display: flex;
        align-items: center;
        padding: 12px;
        border: 1px solid #e4e7ed;
        border-radius: 4px;
        margin-bottom: 8px;
        cursor: pointer;
        transition: all 0.3s;
        
        &:hover {
          background: #f5f7fa;
          border-color: #409eff;
        }
        
        .el-icon {
          font-size: 24px;
          color: #409eff;
          margin-right: 12px;
        }
        
        .doc-info,
        .case-info {
          flex: 1;
          
          .doc-name,
          .case-title {
            font-weight: 500;
            margin-bottom: 4px;
          }
          
          .doc-meta,
          .case-meta {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }
    
    .finance-summary {
      .finance-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 0;
        border-bottom: 1px solid #f0f0f0;
        
        &:last-child {
          border-bottom: none;
        }
        
        .label {
          color: #606266;
        }
        
        .value {
          font-weight: 500;
          
          &.income {
            color: #67c23a;
          }
          
          &.pending {
            color: #e6a23c;
          }
          
          &.total {
            color: #409eff;
          }
        }
      }
    }
  }
}
</style>
